package com.hand.wfive.base;

import android.text.TextUtils;

import com.hand.wfive.loginAndVip.ApiConfig;
import com.hand.wfive.loginAndVip.RsaUtils;

import java.io.IOException;
import java.net.URLDecoder;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class EncryptInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        HttpUrl originalUrl = request.url();
        if (ApiConfig.isEncryptApi(originalUrl.toString())) {
            Request.Builder requestBuilder = request.newBuilder();
            //post请求加密
            if (request.body() instanceof FormBody) {
                FormBody.Builder newFormBody = new FormBody.Builder();//创建新表单
                FormBody oidFormBody = (FormBody) request.body();//请求表单
                //循环取出 request Body 注意FormBody 才会有size属性 FormBody可以满足大部分的请求
                for (int i = 0; i < oidFormBody.size(); i++) {
                    String str = oidFormBody.encodedValue(i);//value
                    String decode = URLDecoder.decode(str);//对value进行URLDecoder解码
                    String s = oidFormBody.encodedName(i);//name
                    String name = URLDecoder.decode(s);//对name进行URLDecoder解码 很重要 这两个都加上 不然取出请求体的时候有的请求体被URLDecoder编码 后台不知道你传过去的是什么
                    /*Log.i("testXX", "----------------str:" + str);
                    Log.i("testXX", "----------------decode:" + decode);
                    Log.i("testXX", "----------------s:" + s);
                    Log.i("testXX", "----------------name:" + name);*/
                    String encrypt = RsaUtils.encryptByPublicKey(decode);
                    if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(encrypt)){
                        newFormBody.add(name.trim(), encrypt.trim());//去空格 相当重要！！都是我踩过的坑
//                        Log.i("testXX", "----------------name encrypt--- "+name+":" + encrypt);
                    }
                }
                requestBuilder.method(request.method(), newFormBody.build());
            }

            // 创建新的请求
            Request newRequest = requestBuilder.build();
            // 继续执行请求
            return chain.proceed(newRequest);
        }
        return  chain.proceed(request);
    }
}
